﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.Globalization;
using BlogsAPI.Abstract;
using Google.Apis.Plus.v1.Data;

namespace BlogsAPI.Search
{
    public class GooglePlus: BasicSearch
    {
        /// <summary>
        /// Уникальный ключ для простых запросов
        /// </summary>
        private String APIkey;

        /// <summary>
        /// Идентификатор любого профиля пользователя в G+
        /// </summary>
        private const String ProfileID = "108978008111493155471";

        public GooglePlus()
        {
            if (ConfigurationManager.AppSettings["GooglePlus"] != null)
            {
                APIkey = ConfigurationManager.AppSettings["GooglePlus"].Split(',')[0];
            }
        }

        public override BlogPost[] SearchFor(string text, DateTime? fromDate)
        {
            return SearchFor(text, fromDate);
        }

        /// <summary>
        /// Все посты с нужным текстом
        /// </summary>
        /// <param name="text">текст для поиска</param>
        /// <param name="fromDate">дата начиная с которой искать объекты, может быть нулом, тогда по максимуму!</param>
        /// <param name="limit">максимальное число результатов в ответе</param>
        /// <param name="twoLetterISOLanguageName">получать результаты только определенного языка</param>
        /// <returns>массив постов удовлетворяющих поиску</returns>
        public BlogPost[] SearchFor(String text, DateTime? fromDate, string twoLetterISOLanguageName = "", uint limit = 0)
        {
            var oRes = new List<BlogPost>();
            try
            {
                var apiHelper = new GooglePlusAPIHelper(ProfileID, APIkey);
                var activities = apiHelper.SearchActivities(text, twoLetterISOLanguageName);

                while (activities.Items.Count > 0)
                {
                    foreach (var activity in activities.Items)
                    {
                        try
                        {
                            if (fromDate != null && activity.Published < fromDate)
                            {
                                return oRes.ToArray();
                            }
                            //activity.Id //activityID
                            var bp = new BlogPost
                            {
                                Comments = (int)activity.Object__.Replies.TotalItems.Value,
                                Existance = true,
                                Link = new Uri(activity.Url+"#"+activity.Id),
                                Links = (int)activity.Object__.Resharers.TotalItems.Value,
                                Published = activity.Published.Value,
                                SpecialParam = activity.Actor.Id,
                                Subject = activity.Actor.DisplayName,
                                Body = activity.Object__.Content,
                                Type = PostType.Public,
                            };
                            if (activity.Location != null && !String.IsNullOrEmpty(activity.Location.DisplayName))
                            {
                                bp.SetParam(PostParams.Tags, activity.Location.DisplayName);
                            }
                            if (activity.Location != null && activity.Location.Position != null)
                            {
                                bp.SetParam(PostParams.Location, String.Format(new CultureInfo("en-US"),
                                            "{0} {1}", activity.Location.Position.Latitude, activity.Location.Position.Longitude));
                            }
                            oRes.Add(bp);

                            
                            if (limit!=0 && oRes.Count >= limit)
                            {
                                return oRes.ToArray();
                            }
                        }
                        catch(Exception e1)
                        {
                            Debug.WriteLine("SearchFor. Something incomplete was found here:/ Text of error: " + e1.Message);
                        }
                    }
                    if (fromDate == null && limit == 0)//нет параметров
                    {
                        return oRes.ToArray();
                    }
                    activities = apiHelper.SearchActivities(text, twoLetterISOLanguageName, activities.NextPageToken);
                }
            }
            catch (Exception e2)
            {
                Debug.WriteLine("SearchFor failed cause " + e2.Message);
            }
            return oRes.ToArray();
        }

    }
}
